<?php
/**
 * Author Yulin
 * Email  dwzhanglong@126.com
 * Date   2016-8-16
 * Func   后台入口
 */
session_start();
header('Content-Type:text/html; charset=UTF-8');
date_default_timezone_set('PRC');
error_reporting(E_ERROR | E_WARNING | E_PARSE);

if (ismobile()){
    // 如果是手机版or移动版的请求，则自动跳转到wap.php页面
    header('Location: ./wap.php');
    die();
}

define('IN_YuLin', true);
define('TIMESTAMP', time());
define('IS_POST',(strtoupper($_SERVER['REQUEST_METHOD']) == 'POST' ? true : false));
define('ROOT_PATH', str_replace('\\', '/', dirname(__FILE__) . '/')); //根目录
define('DATA_PATH', ROOT_PATH . 'data/'); //数据目录
define('LIB_PATH', ROOT_PATH . 'lib/');  //类库文件

include_once LIB_PATH . 'common.inc.php';
require_once LIB_PATH . 'protect.php';
include_once LIB_PATH . 'common.func.php';

//  m、c、a、用来判断路由
$m = NoBadStr($_REQUEST['m']);
$c = NoBadStr($_REQUEST['c']);
$a = NoBadStr($_REQUEST['a']);
!$m && $m = 'index';
!$c && $c = 'index';
!$a && $a = 'index';

!file_exists(ROOT_PATH.'module/'.$m.'/'.$c.'.inc.php') && exit('No input file...');

//	数据库
include(LIB_PATH.'class/Db.class.php');
$db = new DB($_config['db']);

//	模版引擎
include(LIB_PATH.'class/Ytemplate.class.php');
$tpl = new Ytemplate();
$tpl->templateCompile = DATA_PATH.'compile';
$tpl->templateDir = ROOT_PATH.'template';
$tpl->templateExt = 'tpl.php';

//  系统数组
$_Y = [];
$_Y['ip'] = GetIp();
$_user = [];

if($_SESSION['uid'])
{
    $_user          = $db->getrow('SELECT * FROM '.Table('user').' WHERE id = '.$_SESSION['uid']);
    // 检查用户的等级头衔  ==========================
    $_userInfo      = $db->getrow('SELECT truename, email, mobile, qq, wechat, invita_code_id, user_type, level_id, recharge_total, last_take_prize_level FROM ' . Table('user_info') . ' WHERE uid = ' . $_SESSION['uid']);
    if (!$_userInfo['level_id']){
        // 初始一个等级头衔给用户
        $sql        = 'SELECT id FROM ' . Table('user_level') . ' WHERE status = 1 ORDER BY group_point ASC limit 1';
        $levelId    = $db->getrow($sql);
        $sql        = 'UPDATE ' . Table('user_info') . ' SET level_id = ' . $levelId['id'] . ' WHERE uid = ' . $_SESSION['uid'];
        $db->exec($sql);
    }else{
        $levelInfo = $db->getrow('SELECT level, title, group_point, reward, overstep FROM ' . Table('user_level') . ' WHERE id = ' . $_userInfo['level_id']);
        $nextLevel = $db->getrow('SELECT level, title, group_point, reward, overstep FROM ' . Table('user_level') . ' WHERE id > ' . $_userInfo['level_id'] . ' AND status = 1 ORDER BY id ASC limit 1');
    }
    // 载入用户的返点设置信息
    $sql       = '
                SELECT info.`invita_code_id`, inv.`type`, item.`lott_cate_id`, item.`re_point` 
                FROM ' . Table('user_info') . ' AS info
                LEFT JOIN ' . Table('user_invita_code') . ' AS inv
                ON info.`invita_code_id` = inv.`id`
                LEFT JOIN ' . Table('user_invita_item') . ' AS item
                ON inv.`id` = item.`code_id`
                WHERE info.`uid` =' . $_SESSION['uid'];
    $rpsInfo   = $db->getall($sql, 'lott_cate_id');
    
    
    $myOrderList    = $db->getall('SELECT main.`prize`, lott.cate_id
                    FROM ' . Table('lottery_order_main') . ' AS main 
                    LEFT JOIN ' . Table('lottery') . ' AS lott
                    ON main.`lott_id` = lott.`id`
                    WHERE main.uid = ' . $_SESSION['uid']);
    $oftenPlay = array();
    if ($myOrderList){
        foreach ($myOrderList as $mk => $mv){
            $myWinnerAmount['all_prize'] += $mv['prize'];
            if(!in_array($mv['cate_id'], $oftenPlay) && $mv['cate_id']) array_push($oftenPlay, $mv['cate_id']);
        }
    }
    if (!$myWinnerAmount['all_prize'] || $myWinnerAmount['all_prize'] == '0') $myWinnerAmount['all_prize'] = '0.00';
    // 查询所有大彩种
    $sql               = 'SELECT cate.id, cate.`name`, cate.`tags`, cate.`sname`, lott.`id` AS lott_id FROM ' . Table('lottery_category') . ' as cate
                        LEFT JOIN ' . Table('lottery') . ' AS lott
                        ON cate.id = lott.`cate_id`
                        GROUP BY cate.id 
        ';
    $allCate           = $db->getall($sql);
    
	if(!$_user || !$_user['status']){
		unset($_SESSION['uid']);
		unset($_COOKIE['LoginSessionID']);
		set_cookie('LoginSessionID','');
	}
}
// 查询客服链接是否设置
$serviceLink = $db->getrow('SELECT url from ' . Table('weblist') . ' WHERE tid = 1 ORDER BY id DESC limit 1');

$_uid = intval($_SESSION['uid']);
//	彩票种类
$lottery = $db->getall('SELECT * FROM '.Table('lottery').' WHERE status = 1 ORDER BY listorder DESC','id');
$k3 = $db->getall('SELECT * FROM '.Table('lottery').' WHERE status = 1 and ptid="K3" ');
// ========================================================================
$userMoney = $_SESSION['userlast']['money'];
// 查询所有彩种类别
$getCateSql  = 'SELECT * FROM ' . Table('lottery_category') . ' WHERE status = 0';
$cateList    = $db->getall($getCateSql);
$cateIdKey   = array();

foreach ($cateList as $ck => $cv){
    $cateIdKey[$cv['id']] = $cv;
}
// 查询所有彩种
$getLottSql  = 'SELECT * FROM ' . Table('lottery') . ' WHERE status = 1';
$lottList    = $db->getall($getLottSql);
$lottCateKey = array();
// 彩种按照类别Key化
foreach ($lottList as $k => $v){
    $lottCateKey[$v['cate_id']][] = $v;
}
$about = $db->getall('SELECT * FROM '.Table('article').' where cid =9');
include_once(ROOT_PATH.'module/'.$m.'/'.$c.'.inc.php');



//判断是手机登录还是电脑登录
function ismobile() {
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])) return true;

    //此条摘自TPM智能切换模板引擎，适合TPM开发
    if(isset ($_SERVER['HTTP_CLIENT']) &&'PhoneClient'==$_SERVER['HTTP_CLIENT']) return true;
    //如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset ($_SERVER['HTTP_VIA'])) return stristr($_SERVER['HTTP_VIA'], 'wap') ? true : false;

    //判断手机发送的客户端标志,兼容性有待提高
    if (isset ($_SERVER['HTTP_USER_AGENT'])) {
        $clientkeywords = array(
            'nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile'
        );
        //从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
        }
    }
    //协议法，因为有可能不准确，放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT'])) {
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
            return true;
        }
    }
    return false;
}